var ShriChatBoxes = new Array();
var ChatBoxesDiv = new Array(); 
var waitingChatBoxesDiv = new Array();    
var CookieChatBoxesDiv = new Array();    
var base_url = $("div.onlinefriendslist >ul").attr("data");
var soundHandle;
var soundFile = "js/sound/notify.mp3";
var soundFile1 = "js/sound/notify.ogg"; 

	
$(function(){
	$(document).on('click','em.ShchatBarScreenMinimize',function(){
		$(this).parents('div.ShchatBarBoxTitle').siblings(".ShchatBarBox").toggle();
		InitiateCookie();
	});

	function InitiateCookie(){
		$.cookie("rskesre", null);
		$('.ShChatBoxlisting').each(function(){
			var iids = $(this).attr('id');
			$uname = $("#"+iids+" > .ShchatBarBoxTitle > .ShchatBarBoxTitleTextOption span a").attr('href');
			$title = $("#"+iids+" > .ShchatBarBoxTitle > .ShchatBarBoxTitleTextOption span").html();
			$olst  = $("#"+iids+" > .ShchatBarBoxTitle > .ShchatBarBoxTitleTextOption em").attr('class');
			$action  = $("#"+iids+" > .ShchatBarBox > .ShchatBarBoxToolbar > .ShchatBarBoxToolbarSettings em").attr('name');
			$state = $("#"+iids+" > .ShchatBarBox").css('display');
			$threadid  = $("#"+iids+" > .ShchatBarBoxTitle").attr("id");
			$position = $("#"+iids).css('right');
			$st = '1';
			if($state != 'none'){$st = '0';}
			if($.cookie("rskesre")){
				$OldSet = $.cookie("rskesre");
				$newSet = $OldSet+"|"+iids+"_"+$title+"_"+$olst+"_"+$st+"_"+$position+"_"+$threadid;  
				$.cookie("rskesre", null);
				$.cookie("rskesre", $newSet);
			}else{
				$newSet = iids+"_"+$title+"_"+$olst+"_"+$st+"_"+$position+"_"+$threadid;  
				$.cookie("rskesre", $newSet);
			}
		});
	}

	$(document).on('click','.ShchatBarScreenClose',function(){
		$(this).attr('class','');
		$thisid = $(this).parents('div.ShChatBoxlisting').attr('id');
		$MeCss = $(this).parents('div.ShChatBoxlisting').css('right');
		$(this).parents('div.ShChatBoxlisting').remove();
		$('.S-ShChatBoxlisting').each(function(){
			var iids = $(this).attr('id');
			waitingChatBoxesDiv.push(iids);
		});
		if(waitingChatBoxesDiv.length > 0){
			$DvID = $('#FrmXSet34234').children('.S-ShChatBoxlisting:first-child').attr('id');
			$waitingDvContent = $('#'+$DvID).html();
			$('#'+$DvID).remove();
			$('<div class="ShChatBoxlisting" id="'+$DvID+'" name="1">'+$waitingDvContent+'</div>').appendTo("body");
			$("#"+$DvID).css('right',$MeCss);
			$('#FrmXSet34234').find('div').first().remove();
			waitingChatBoxesDiv.length = 0;
			$('.S-ShChatBoxlisting').each(function(){
				var iids = $(this).attr('id');
				waitingChatBoxesDiv.push(iids);
			});
			InitiateCookie();
		}else{
			ChatBoxesDiv.length = 0;
			$('.ShChatBoxlisting').each(function(){
					var iids = $(this).attr('id');
					var index= $.inArray(iids, ChatBoxesDiv);
					if(index == -1){ChatBoxesDiv.push(iids);}
			});
			$ChatBoxCount = ChatBoxesDiv.length;
			if($ChatBoxCount < 3 && $ChatBoxCount > 0 ){
			$bx1id = ChatBoxesDiv[0];
			$bx2id = ChatBoxesDiv[1];
			$("#"+$bx1id).css('right',280);
			$raxis = (1+1)*(280);
			$("#"+$bx2id).css('right',$raxis);
			}
			InitiateCookie();
		}
	});//ends		

/************open new chat window Start*************/
	$(document).on('click','.switchFriendsChatWindow',function(){
		$ChatBoxIndexusername	 = $(this).attr('rel');
		$ChatBoxIndexId			 = $(this).attr('id');
		$elementName 			 = $(this).attr('name');
		$action 				 = $(this).attr('target');
		$status 				 = $(this).attr('datacheck');
		$ChatBoxIndextitle 		 = $(this).attr('datastr');//$(this).children('span#ChatUserName').html();// user display name
		$ChatBoxCount 			 = $('.ShChatBoxlisting').length;
		if($ChatBoxIndextitle=="undefined"){
			$ChatBoxIndextitle = $(this).attr('datastr');//$(this).children('span#ChatUserName').html();
		}
		if ($("#ShChatBox"+$ChatBoxIndexId).length == 0){
			$('.ShChatBoxlisting').each(function(){
				var iids  = $(this).attr('id');
				var index = $.inArray(iids, ChatBoxesDiv);
				if(index == -1){ChatBoxesDiv.push(iids);}
			});
			$raxis = ($ChatBoxCount+1)*(280);
			if($ChatBoxCount == 0){$raxis = 280;}   
			if($('.ShChatBoxlisting').length < 3){
				InitiateChatThreadBox($ChatBoxIndexId,$ChatBoxIndextitle,$elementName,$raxis,0,0,$action,$ChatBoxIndexusername,$status);
				InitiateCookie();
			}else{
				InitiateChatThreadBox($ChatBoxIndexId,$ChatBoxIndextitle,$elementName,$raxis,0,1,$action,$ChatBoxIndexusername,$status);
				$boxId1 = ChatBoxesDiv[0];
				$boxId2 = ChatBoxesDiv[1];
				$boxId3 = ChatBoxesDiv[2];
				$firstPosition = $("#"+$boxId1).css('right');
				$SecndPosition = $("#"+$boxId2).css('right');
				$ThirdPosition = $("#"+$boxId3).css('right');
				$("#"+$boxId2).css('right',$firstPosition);
				$("#"+$boxId3).css('right',$SecndPosition);
				$("#"+$boxId1).hide();
				$("#"+$boxId1).css('right','');
				$("#ShChatBox"+$ChatBoxIndexId).show();
				$("#ShChatBox"+$ChatBoxIndexId).css('right',$ThirdPosition);
				$firstBoxData = $("#"+$boxId1).html();
				$("#"+$boxId1).remove();
				ChatBoxesDiv.length = 0;
				$('.ShChatBoxlisting').each(function(){
					var iids = $(this).attr('id');
					var index= $.inArray(iids, ChatBoxesDiv);
					if(index == -1){ChatBoxesDiv.push(iids);}
				});
				$('<div class="S-ShChatBoxlisting" id="'+$boxId1+'" style="display:none;" name="1">'+$firstBoxData+'</div>').appendTo("#FrmXSet34234");
				InitiateCookie();
			}
		}else{
			if($("#ShChatBox"+$ChatBoxIndexId).css('display')=='none'){
				$boxId1 = ChatBoxesDiv[0];
				$boxId2 = ChatBoxesDiv[1];
				$boxId3 = ChatBoxesDiv[2];
				$firstPosition = $("#"+$boxId1).css('right');
				$SecndPosition = $("#"+$boxId2).css('right');
				$ThirdPosition = $("#"+$boxId3).css('right');
				$("#"+$boxId2).css('right',$firstPosition);
				$("#"+$boxId3).css('right',$SecndPosition);
				$("#"+$boxId1).hide();
				$("#"+$boxId1).css('right','');
				$firstBoxData = $("#"+$boxId1).html();
				$("#"+$boxId1).remove();
				$('<div class="S-ShChatBoxlisting" id="'+$boxId1+'" style="display:none;" name="1">'+$firstBoxData+'</div>').appendTo("#FrmXSet34234");
				$hiddenBoxData = $("#ShChatBox"+$ChatBoxIndexId).html();
				$("#ShChatBox"+$ChatBoxIndexId).remove();
				$('<div class="ShChatBoxlisting" id="ShChatBox'+$ChatBoxIndexId+'" name="1">'+$hiddenBoxData+'</div>').appendTo("body");
				$("#ShChatBox"+$ChatBoxIndexId).css('right',$ThirdPosition);
				ChatBoxesDiv.length = 0;
			$('.ShChatBoxlisting').each(function(){
				var iids = $(this).attr('id');
				var index= $.inArray(iids, ChatBoxesDiv);
				if(index == -1){ChatBoxesDiv.push(iids);}
			});	
			InitiateCookie();
		}
	 }
	//	addInArray($ChatBoxIndexId,$elementName);
	});
/************open new chat window End*************/
});

function PresetInitialBlockThread(thread_id){
var userssid = thread_id.replace('olFrnList-','');
var chatbox_id = 'ShChatBoxolFrnList-'+userssid;
$("#ol_user-"+userssid).removeClass('usermessagealert');
var chk_chat_box = $('#'+chatbox_id).attr('name');
chk_chat_box = parseInt(chk_chat_box);
$('#'+chatbox_id).attr('name','1');
$("body").attr("datafirst"+thread_id,"1");
 var userid = $('#sControlSpan').attr("name");
var datatsr = 'thread='+thread_id+'&userssid='+userid;
			$.ajax({
			type: 'POST',
			url: base_url+'ajaxhandler/get_messages',
			data: datatsr,
			dataType: 'json',
			cache: false,
			success: function(result){
						if(result.status==200){
							var list='';
							$.each( result.response, function( key, value ) {
								
								var msg_actual_time = value["msgtime"];
								list = list+'<li target="'+value['sender_id']+'" name="'+msg_actual_time+'" class="messageListline" id="list-'+value['msg_id']+'"><div class="threadmsgcontainerleft clearfix"><div id="left" class="messagelineimg imgTip"><img src="'+base_url+'image_controller/get_thumbs/'+value['profile_pic_id']+'/" rel="'+value['first_name']+' '+value['last_name']+'"></div><div id="middle" class="clearfix"><div class="threadmsg"><div class="UserChatMsgOptions clearfix"><div class="UserChatmsgTimeSpan timespan">'+value['timeago']+'</div><div class="editoptionsDelete" id="'+value['msg_id']+'"></span></div></div><div class="ChatUserMessagediv"><pre>'+value['message']+'</pre></div></div></div></div></li>';
							});
							$("#ful_ol_conv_ul-"+thread_id).html(list);
							var height = $("#ful_ol_conv_ul-"+thread_id).parent().prop('scrollHeight');
							$("#ful_ol_conv_ul-"+thread_id).parent().scrollTop(height);
						}else{
						$("#ful_ol_conv_ul-"+thread_id).html('<li id="conversationLoadingmsg-'+thread_id+'" style="border: none;"><span class="conversationLoadingmsg">'+result.msg+'<span></li>');
						}
						$("body").attr("datafirst"+thread_id,false);
				}
			});
}

function InitiateChatThreadBox($ChatBoxIndexId,$ChatBoxIndextitle,$elementName,$raxis,$state,$show,$action,$chatusername,$olstats){
$personId = $ChatBoxIndexId.replace('olFrnList-','');
$ChatBoxCount = $('.ShChatBoxlisting').length;
$innitialState = '';
if($show == '1'){$innitialState = 'display:none;';} 
$MinState = '';
	if($state == 1){$MinState = 'style="display:none;"';}
	$stat = '<li class="clearmsgbox" data="ShChatBox'+$ChatBoxIndexId+'" datastr="'+$elementName+'">Clear messages</li>'; 
	//if($action =='U'){ $stat = 'Unblock User'; } //$olstats =1;
	if($olstats == 0){ $statusclass = 'unavailable';}else{ $statusclass = 'available';}
	//var base_url = $("div.friendslist > ul").attr("data");
	$('<div class="ShChatBoxlisting" id="ShChatBox'+$ChatBoxIndexId+'" style="right:'+$raxis+'px; '+$innitialState+'"><div class="ShchatBarBoxTitle clearfix" id="ShchatBarBoxTitle-'+$elementName+'" name="'+$ChatBoxIndexId+'"><div class="ShchatBarBoxTitleTextOption clearfix"><em class="'+$statusclass+'"></em><span><a id="GSB766YUG" href="./profile/?id='+$chatusername+'">'+$ChatBoxIndextitle+'</a></span></div><div id="left" class="typingstatusLeftDiv-'+$elementName+'" style="display: none;"><span style="display: none;" class="typingstatus_box clearfix"><em style="background-position: -1116px -136px;"></em><span></span></span></div><div class="ShchatBarBoxTitleScreenOption clearfix"><em class="ShchatBarScreenClose"></em><em class="ShchatBarScreenMinimize"></em></div></div><div class="ShchatBarBox" id="ck" '+$MinState+'><div class="ShchatBarBoxToolbar clearfix"><span class="ShchatBarBoxToolbarSettings"><em class="showChatSettings"></em><div class="ShchatBarBoxToolbarSettingsOption"><ul>'+$stat+'</ul></div></span></div><div class="ShchatBarBoxScreenWindow clearfix"><ul class="ShchatBarBoxScreenWindowTexts" id="ful_ol_conv_ul-'+$elementName+'"><li id="conversationLoadingmsg-'+$elementName+'" style="border: none;"><span class="conversationLoadingmsg">Loading Conversation</span></li></ul></div><div class="ShchatBarBoxcomposeWindow clearfix"><textarea class="ShchatBarBoxcomposeInput" name="'+$ChatBoxIndexId+'" id="ShchatBarBoxcomposeInput-'+$elementName+'" target="0" spellcheck="false"></textarea></div></div></div>').appendTo("body");
}


function InitiateCookiesChatThreadBox($ChatBoxIndexId,$ChatBoxIndextitle,$elementName,$raxis,$olstate,$show,$action,$chatusername,$olstats){
if($("#"+$ChatBoxIndexId).length==0){
	$personId = $ChatBoxIndexId.replace('ShChatBoxolFrnList-','');
	$personname = $ChatBoxIndexId.replace('ShChatBox','');
	$OLLIId = $elementName.replace('ShchatBarBoxTitle-','');
	$MinState = '';
	if($show == 1){$MinState = 'style="display:none;"';}
	$stat = '<li class="clearmsgbox" data="ShChatBox'+$ChatBoxIndexId+'" datastr="'+$OLLIId+'">Clear messages</li>'; 
	//if($action =='U'){ $stat = 'Unblock User'; } 
	//$olstats =1;
	if($olstats == 0){ $statusclass = 'unavailable';}else{ $statusclass = 'available';}
	$('<div class="ShChatBoxlisting" id="'+$ChatBoxIndexId+'" style="right:'+$raxis+';"><div class="ShchatBarBoxTitle clearfix" id="ShchatBarBoxTitle-'+$OLLIId+'" name="'+$ChatBoxIndexId+'"><div class="ShchatBarBoxTitleTextOption clearfix"><em class="'+$statusclass+'"></em><span><a id="GSB766YUG" href="./profile.php?user='+$chatusername+'">'+$ChatBoxIndextitle+'</a></span></div><div id="left" class="typingstatusLeftDiv-'+$OLLIId+'" style="display: none;"><span style="display: none;" class="typingstatus_box clearfix"><em style="background-position: -1116px -136px;"></em><span></span></span></div><div class="ShchatBarBoxTitleScreenOption clearfix"><em class="ShchatBarScreenClose"></em><em class="ShchatBarScreenMinimize"></em></div></div><div class="ShchatBarBox" id="ck" '+$MinState+'><div class="ShchatBarBoxToolbar clearfix"><span class="ShchatBarBoxToolbarSettings"><em class="showChatSettings"></em><div class="ShchatBarBoxToolbarSettingsOption"><ul>'+$stat+'  </ul></div></span></div><div class="ShchatBarBoxScreenWindow clearfix"><ul class="ShchatBarBoxScreenWindowTexts" id="ful_ol_conv_ul-'+$OLLIId+'"><li id="conversationLoadingmsg-'+$OLLIId+'" style="border: none;"><span class="conversationLoadingmsg">Loading Conversation</span></li></ul></div><div class="ShchatBarBoxcomposeWindow clearfix"><textarea class="ShchatBarBoxcomposeInput" name="'+$personname+'" id="ShchatBarBoxcomposeInput-'+$OLLIId+'" target="0" spellcheck="false"></textarea></div></div></div>').appendTo("body");
	PresetInitialBlockThread($OLLIId)
	}
}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(function(){
recursiveData(); 
recursiveOnlineData(); 

/***************Tool tip Start*******************/
$('.imgTip img').on('mouseenter',function(event){
$data = $(this).attr('rel');
$('<span class="imgTipcontainer"><div style="position:relative;">'+$data+'<em class="toolTipArrow"></em></div></span>').appendTo('body');
$('span.imgTipcontainer').hide();
$SpWidth = $('span.imgTipcontainer').width();
var position = $(this).offset();	
	var tooltipX = position.left - ($SpWidth+25);
	var tooltipY = position.top;
	$('span.imgTipcontainer').css({top: tooltipY, left: tooltipX});
	$('span.imgTipcontainer').fadeIn(200);
});

$('.imgTip img').on('mouseleave',function(){
$('span.imgTipcontainer').remove();
});
/*************** Tool tip End *******************/

if($.cookie("rskesre")){
	$CookieState = $.cookie("rskesre");
	$CookieState = decodeURIComponent($CookieState);
	$CookiesAray = $CookieState.split("|");
	for($i=0;$i < $CookiesAray.length;$i++){
		$PresetCookie = $CookiesAray[$i].split("_");
		$CookieID = $PresetCookie[0];
		$CookieTitle = $PresetCookie[1];
		$CookieOlStatus = $PresetCookie[2];
		$CookieStatus = $PresetCookie[3];
		$CookiePosition = $PresetCookie[4];
		$CookieElementName = $PresetCookie[5];
		//$CookieAction = $PresetCookie[6];
		InitiateCookiesChatThreadBox($CookieID,$CookieTitle,$CookieElementName,$CookiePosition,$CookieOlStatus,$CookieStatus,'');
	}
}
$(document).on('click',".switchFriendsChatWindow",function(){
	var userssid = $(this).attr('id').replace('olFrnList-','');
	var chatbox_id = 'ShChatBoxolFrnList-'+userssid;
	var chk_chat_box = $('#'+chatbox_id).attr('name');
	chk_chat_box = parseInt(chk_chat_box);
	if($('#'+chatbox_id).length == 1 && chk_chat_box != 1){
		$('#'+chatbox_id).attr('name','1');
		var thread_id = $(this).attr('name');
		$("body").attr("datafirst"+thread_id,"1");
		var userid = $('#sControlSpan').attr("name");
		var datatsr = 'thread='+thread_id+'&userssid='+userid;
		$.ajax({
		type: 'POST',
		url: base_url+'ajaxhandler/get_messages',
		data: datatsr,
		dataType: 'json',
		cache: false,
		success: function(result){
					if(result.status==200){
							var list='';
							$.each( result.response, function( key, value ) {
								//var msg_actual_time = new Date(value["created_date"].replace(' ', 'T')).getTime();
								var msg_actual_time = value["msgtime"];
								list = list+'<li target="'+value['sender_id']+'" name="'+msg_actual_time+'" class="messageListline" id="list-'+value['msg_id']+'"><div class="threadmsgcontainerleft clearfix"><div id="left" class="messagelineimg imgTip"><img src="'+base_url+'image_controller/get_thumbs/'+value['profile_pic_id']+'/" rel="'+value['first_name']+' '+value['last_name']+'"></div><div id="middle" class="clearfix"><div class="threadmsg"><div class="UserChatMsgOptions clearfix"><div class="UserChatmsgTimeSpan timespan">'+value['timeago']+'</div><div class="editoptionsDelete" id="'+value['msg_id']+'"></span></div></div><div class="ChatUserMessagediv"><pre>'+value['message']+'</pre></div></div></div></div></li>';
							});
							$("#ful_ol_conv_ul-"+thread_id).html(list);
							var height = $("#ful_ol_conv_ul-"+thread_id).parent().prop('scrollHeight');
							$("#ful_ol_conv_ul-"+thread_id).parent().scrollTop(height);
						}else{
						$("#ful_ol_conv_ul-"+thread_id).html('<li id="conversationLoadingmsg-'+thread_id+'" style="border: none;"><span class="conversationLoadingmsg">No recent conversation<span></li>');
						}
						$("body").attr("datafirst"+thread_id,0);	
			
			}
			});
}
});



$(document).on('click',".showChatSettings",function(){
$(this).next('.ShchatBarBoxToolbarSettingsOption').toggle();
$(this).toggleClass('SettingIconClicked');
});


$(document).on('keydown','.ShchatBarBoxcomposeInput',function(event){
	var my_img_icon = $(".PipeLoaderIm").html();//Its my Id
	$meId = $(this).attr('id'); $Me = $('#'+$meId);
	if(event.keyCode == 13 && event.shiftKey == 0){
		var ts = Math.round((new Date()).getTime() / 1000);
		var msg = $(this).val();	
		msg = msg.replace(/^\s+|\s+$/g,"").replace(/\n/g, "<br/>");
		if(msg != ''){
			var contrl_num = $("#sControlSpan").attr('target');
			if(contrl_num == '0'){
				msg = encodeURIComponent(msg);
				var thread_id = $(this).attr('id').replace('ShchatBarBoxcomposeInput-','');
				var lastime = $("#ful_ol_conv_ul-"+thread_id+" li").last().attr('name');
				var lastmsgid = $("#ful_ol_conv_ul-"+thread_id+" li").last().attr('id').replace('list-','');
				var fid = $(this).attr('name').replace('olFrnList-','');
				var datastr = 'thread='+thread_id+'&newmsg='+msg+'&lastime='+lastime+'&fid='+fid+'&lastmsgid='+lastmsgid;
	
				var height_2 = $("#ful_ol_conv_ul-"+thread_id).parent().prop('scrollHeight');
				$("#ful_ol_conv_ul-"+thread_id).parent().scrollTop(height_2);
				$.ajax({type: "POST",
					url: base_url+'ajaxhandler/send_chatmsg',
					dataType: "json",
					data: datastr,
					cache: false, success: function(result){
					/* if(result.status == 200){
						var list =''
						$.each(result.response, function( key, value ) {
							list = list+'<li name="'+value['msgtime']+'" class="messageListline" id="list-'+value['msg_id']+'"><div class="threadmsgcontainerleft clearfix"><div id="left" class="messagelineimg"><img src="data:image/jpg;base64,'+my_img_icon+'"></div><div id="middle" class="clearfix"><div class="threadmsg"><div class="UserChatMsgOptions clearfix"><div class="UserChatmsgTimeSpan timespan">'+value['created_date']+'</div><div class="editoptionsDelete" id="'+value['message']+'"><span class="instantDelete"></span></div></div><div class="ChatUserMessagediv"><pre>'+value['message']+'</pre></div></div></div></div></li>';
						});
						if(result.remove_li == 'yes'){
							$("#ful_ol_conv_ul-"+thread_id+" li").last().remove();
						}
						//$("#conversationLoadingmsg-"+thread_id).remove();
						//$("#ful_ol_conv_ul-"+thread_id).append(list);
						var height	= $("#ful_ol_conv_ul-"+thread_id).parent().prop('scrollHeight');
						$("#ful_ol_conv_ul-"+thread_id).parent().scrollTop(height);
					
						}else{
					
						}*/
					}
				});
			}
		$Me.val("");
		$Me.focus();
		}
	return false;
	}
});
$(".messageRead").on("click",function(){
	var thread = $(this).attr("name");
	var uid = $(this).attr("id").replace("olFrnList-","");
	var datastr = "thread="+thread+"&id="+uid;
	$.ajax({type: "POST",
					url: base_url+'ajaxhandler/read_msg',
					dataType: "json",
					data: datastr,
					before:function(){},
					cache: false, success: function(result){
						if(result.status=200){
							var da = result.result
							var unread = parseInt($("#unreadmsg"+uid).html());
							var totalmsg  = parseInt($(".msgcount").html());
							totalmsg = totalmsg - unread;
							$(".msgcount").html(totalmsg);
							$("#unreadmsg"+uid).html(0)
						}
					}
					});
});

$(document).on("click",".clearmessagetrash",function(){
		var con = confirm("Do you really want delete all messages?");
		if(con==false){return false;}
		$thread = $(this).attr("name");
		$myid = $(this).attr("data");
		var datastr = "threads="+$thread+'&mine='+$myid;
		$.ajax({type: "POST", url: base_url+'ajaxhandler/emptythread', dataType: "json",data: datastr, cache: false, success: function(res){
			
			if(res.status=='200'){
				msgalert(res.result,'success');
				//alert(res.my1 +' get it ' +res.my2);
				location.reload(true);
			}else{
				msgalert(res.result,'error');
			}	
		}
		});
	});
	$(document).on("click",".clearmsgbox",function(){
		var con = confirm("Do you really want clear message box?");
		if(con==false){return false;}
		//$thread = $(this).attr("name");
		$thread = $(this).attr("datastr");
		$myid = $(this).attr("data");
		$("#ful_ol_conv_ul-"+$thread).find("li").css("display","none");
		$(".showChatSettings").click();
		/*$.ajax({type: "POST", url: base_url+'ajaxhandler/emptythread', dataType: "json",data: datastr, cache: false, success: function(res){
			
			if(res.status=='200'){
				msgalert(res.result,'success');
				location.reload(true);
			}else{
				msgalert(res.result,'error');
			}	
		}
		});*/
	});

});/*********Document*ready*closed************/




function recursiveData(){
	var check = $(".ShChatBoxlisting");
	 if(check.length>0){
		check.each(function(){
			$datathread = $(this).find('div:first').attr("id").replace("ShchatBarBoxTitle-",'');
			var myid = $('#sControlSpan').attr("name");
			if($("body").attr("datafirst"+$datathread)=="1"){ return false; }
			$msgid = $(this).find('.ShchatBarBox li:last').attr("id").replace("list-",'');
			$msgtime = $(this).find('.ShchatBarBox li:last').attr("name");
			
			var datastr ="thread="+$datathread+"&msgid="+$msgid+"&lastmsgtime="+$msgtime+"&userid="+myid;
			if($("body").attr("data"+$datathread)==true){return false;}
			$("body").attr("data"+$datathread,true);
			$.ajax({type: "POST",
					url: base_url+'ajaxhandler/newmsgpull',
					dataType: "json",
					data: datastr,
					before:function(){},
					cache: false, success: function(result){
						if(result.status == 200){
							var list ='';
							
							$.each(result.result, function(key, value) {
								list = '<li name="'+value['msgtime']+'" class="messageListline" id="list-'+value['msg_id']+'"><div class="threadmsgcontainerleft clearfix"><div id="left" class="messagelineimg imgTip"><img rel="'+value['first_name']+' '+value['last_name']+'" src="'+value['sender_pic']+'"></div><div id="middle" class="clearfix"><div class="threadmsg"><div class="UserChatMsgOptions clearfix"><div class="UserChatmsgTimeSpan timespan">'+value['timeago']+'</div></div><div class="ChatUserMessagediv"><pre>'+value['message']+'</pre></div></div></div></div></li>';
								//<div class="editoptionsDelete" id="'+value['msg_id']+'"><span class="instantDelete"></span></div>
								if($("#list-"+value['msg_id']).length<1){
									$("#ful_ol_conv_ul-"+result.thread).append(list);
								}
							});
							$("#conversationLoadingmsg-"+result.thread).remove();
							$("#ful_ol_conv_ul-"+result.thread).find(".waiting").remove();
							//$("#ful_ol_conv_ul-"+result.thread).append(list);
							
							playSound();
							var height	= $("#ful_ol_conv_ul-"+result.thread).parent().prop('scrollHeight');
							$("#ful_ol_conv_ul-"+result.thread).parent().scrollTop(height);
						}
						$("body").attr("data"+$datathread,false);
						
					}
				});
				
			
		});
	}
	setTimeout('recursiveData()',1000);
}



function recursiveOnlineData(){
	var base_url = $(".onlinefriendslist ul").attr("data");
	var timefrom = $(".onlinefriendslist ul").attr("name");
	var myid = $(".onlinefriendslist ul").attr("datastr");
	var datastr = "time="+timefrom+"&my="+myid;
	$.ajax({type: "POST",
			url: base_url+'ajaxhandler/onlineusers',
			dataType: "json",
			data: datastr,
			before:function(){},
			cache: false, success: function(result){
				if(result.status==200){
					
					$html = '';
					$html1 = $(".onlinefriendslist ul").get();
					$online = $("#sControlSpan").html();
					$i=0;
					console.log($html1[0]['children']);
					$.each($html1[0]['children'], function(key1, value1) {
						
						$.each(result.result.online, function(key, value) {
						
							$name = value.first_name+' '+value.last_name;
							$pic = base_url+"image_controller/get_thumbs/"+value.profile_pic_id;
							if(value1['children'][2]['innerText'] != $name){
							$html += $online.replace(/{email}/g,value.email).replace(/{thread}/g,value.thread_id).replace(/{reciver}/g,value.reciver).replace(/{name}/g,$name).replace(/{profile_pic}/g,$pic);
							
							}
							$i++;
						});
					});
					
					console.log($html);
					$(".chatfriendheader span").html("Online friends("+$i+")");
					//$(".onlinefriendslist ul").html($html);
					$.each(result.result.newmsg, function(key, value) {
						
						$("li#olFrnList-"+value).click();
					});
				}else if(result.status==201){
					$(".chatfriendheader span").html("Online friends(0)");
					$(".onlinefriendslist ul").html("");
				}
			}
			});
	setTimeout('recursiveOnlineData()',3000);
}








function setBrowserTitle(name) {
	document.title=name+" says...";
}
function playSound(){
  soundHandle = document.getElementById('soundHandle');
  soundHandle.src = soundFile;   // for google chrome mp3
  soundHandle.play();
  soundHandle.src = soundFile1;  // for firefox and opera ogg
  soundHandle.play();	

}